package com.share.rules.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.utils.bean.BeanUtils;
import com.share.rules.config.DroolsHelper;
import com.share.rules.domain.*;
import com.share.rules.mapper.FeeRuleMapper;
import com.share.rules.service.IFeeRuleService;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
public class FeeRuleServiceImpl extends ServiceImpl<FeeRuleMapper, FeeRule> implements IFeeRuleService {
    @Autowired
    private KieContainer kieContainer;
    @Autowired
    private FeeRuleMapper feeRuleMapper;

    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        //封装传入对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDurations(feeRuleRequestForm.getDuration());
        log.info("传入参数：{}", JSON.toJSONString(feeRuleRequest));

        //获取最新订单费用规则
        FeeRule feeRule = feeRuleMapper.selectById(feeRuleRequestForm.getFeeRuleId());
        KieSession kieSession = DroolsHelper.loadForRule(feeRule.getRule());

        //封装返回对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse", feeRuleResponse);
        // 设置订单对象
        kieSession.insert(feeRuleRequest);
        // 触发规则
        kieSession.fireAllRules();
        // 中止会话
        kieSession.dispose();
        log.info("计算结果：{}", JSON.toJSONString(feeRuleResponse));

        //封装返回对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();

        feeRuleResponseVo.setTotalAmount(new BigDecimal(feeRuleResponse.getTotalAmount())); //总金额
        feeRuleResponseVo.setFreePrice(new BigDecimal(feeRuleResponse.getFreePrice())); //折扣金额
        feeRuleResponseVo.setExceedPrice(new BigDecimal(feeRuleResponse.getExceedPrice())); //需支付金额
        feeRuleResponseVo.setFreeDescription(feeRuleResponse.getFreeDescription()); //折扣描述
        feeRuleResponseVo.setExceedDescription(feeRuleResponse.getExceedDescription()); //需支付金额描述

        return feeRuleResponseVo;
    }
}
